package com.sy.protocal;

import com.sy.messages.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

/**
 * @Author yumax
 * @Date 2024 01 16 11 43
 * 必须和LengthFieldBasedFrameDecoder一起使用，确保收到的消息是完整的
 **/
@Slf4j
@ChannelHandler.Sharable
public class MessageCodecSharable extends MessageToMessageCodec<ByteBuf, Message> {
    @Override
    protected void encode(ChannelHandlerContext ctx, Message message, List<Object> list) throws Exception {
        final ByteBuf byteBuf = ctx.alloc().buffer();
        //1. 4字节的魔数
        byteBuf.writeBytes(new byte[]{1, 2, 3, 4});
        //2. 1字节的版本
        byteBuf.writeByte(1);
        //3. 1字节的序列化方式 0:jdk, 1:json
        byteBuf.writeByte(0);
        //4. 1字节的指令类型
        byteBuf.writeByte(message.getMessageType());
        //5. 4个字节sequenceId
        byteBuf.writeInt(message.getSequenceId());

        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        final ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        objectOutputStream.writeObject(message);
        final byte[] bytes = outputStream.toByteArray();

        //6. 长度
        byteBuf.writeInt(bytes.length);
        //7. 字节内容
        byteBuf.writeBytes(bytes);

        list.add(byteBuf);
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf buf, List<Object> list) throws Exception {
        final int magicNum = buf.readInt();
        final byte version = buf.readByte();
        final byte serializeType = buf.readByte();
        final byte messageType = buf.readByte();
        final int sequenceId = buf.readInt();

        final int length = buf.readInt();
        final byte[] bytes = new byte[length];
        buf.readBytes(bytes, 0, length);

        final ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
        final Message msg = (Message) objectInputStream.readObject();
        log.debug("{}", msg);
    }
}
